//
//  ZYMessaegDetailVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/2.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYMessageDetailVC.h"
#import "ZYMessageDetailViewCell.h"
#import "ZYMessage.h"
#import "ZYMessageViewModel.h"
#import "ZYNavigationView.h"
#import "UITableView+FDTemplateLayoutCell.h"

#define kMessageCellItemID @"kMessageCellItemID"

@interface ZYMessageDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray<ZYMessage *> *messageArray;
@property(nonatomic,strong) ZYMessageViewModel *viewModel;

/**
 需要删除的消息
 */
@property(nonatomic,strong) ZYMessage *deleteMessage;

/**
 消息数量
 */
@property(nonatomic,assign) NSInteger count;
@end

@implementation ZYMessageDetailVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationView setBottomViewBgColor:RGBA(248, 248, 248, 1)];
    if(_messageType == ZYMessageTypeSystem){
        self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_MESSAGE_TYPE_SYSTEM];
        [self.viewModel loadSystemMessageList];
    }else{
        self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_MESSAGE_TYPE_DEVICE];
        [self.viewModel loadUserMessageList];
    }
}

#pragma mark -init
-(void)setup{
    _count = 0;
    [self setupTableView];
    [self bindView];
    if(self.messageType == ZYMessageTypeDevice){
        [self.viewModel loadUserMessageList];
    }else{
        [self.viewModel loadSystemMessageList];
    }
}

-(void)bindView{
    @weakify(self);
    //获取消息列表
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        self.count = 0;
        if(self.messageType == ZYMessageTypeDevice){
            [self.viewModel loadUserMessageList];
        }else{
            [self.viewModel loadSystemMessageList];
        }
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        if(self.messageType == ZYMessageTypeDevice){
            [self.viewModel loadMoreUserMessageList];
        }else{
            [self.viewModel loadMoreSystemMessageList];
        }
    }];
    [[[self.viewModel.systemMessageCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.messageArray = x;
        for (ZYMessage *message in x) {
            message.messageType = ZYMessageTypeSystem;
        }
        if([x count] == self.count){
            self.tableView.mj_footer.hidden = YES;
        }
        self.count = [x count];
        [self.tableView reloadData];
        //标记已读
        self.viewModel.modifyArray = x;
        [self.viewModel.modifyReadCommand execute:nil];
    }];
    
    [[[self.viewModel.userMessageCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.messageArray = x;
        for (ZYMessage *message in x) {
            message.messageType = ZYMessageTypeDevice;
        }
        if([x count] == self.count){
            self.tableView.mj_footer.hidden = YES;
        }
        self.count = [x count];
        [self.tableView reloadData];
        //标记已读
        self.viewModel.modifyArray = x;
        [self.viewModel.modifyReadCommand execute:nil];
    }];
    [self.viewModel.userMessageCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    [self.viewModel.userMessageCommand.executing subscribeNext:^(id isExcuting) {
        @strongify(self);
        if (![isExcuting boolValue]) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    [self.viewModel.systemMessageCommand.executing subscribeNext:^(id isExcuting) {
        @strongify(self);
        if (![isExcuting boolValue]) {
            if(self.tableView.mj_header.isRefreshing){
                [self.tableView.mj_header endRefreshing];
            }
            if(self.tableView.mj_footer.isRefreshing){
                [self.tableView.mj_footer endRefreshing];
            }
        }
    }];
    
    //删除
    [self.viewModel.deleteMessageCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        [self.messageArray removeObject:self.deleteMessage];
        [self.tableView reloadData];
    }];
    [self.viewModel.deleteMessageCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
    
    //标记消息是否已读
    [self.viewModel.modifyReadCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
}

-(void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.height)];
    [self.view addSubview:_tableView];
    _tableView.top = self.navigationView.bottom;
    [_tableView registerClass:[ZYMessageDetailViewCell class] forCellReuseIdentifier:kMessageCellItemID];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = RGBA(248, 248, 248, 1);
    _tableView.fd_debugLogEnabled = YES;
    NSLog(@"%ld",self.messageArray.count);
    [_tableView reloadData];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView fd_heightForCellWithIdentifier:kMessageCellItemID cacheByIndexPath:indexPath configuration:^(ZYMessageDetailViewCell *  cell) {
        cell.fd_enforceFrameLayout = NO;
        cell.message = self.messageArray[indexPath.row];
    }];
//    return 200;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYMessageDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMessageCellItemID];
    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = [[ZYMessageDetailViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kMessageCellItemID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZYMessage *message = self.messageArray[indexPath.row];
    cell.fd_enforceFrameLayout = NO;
    cell.message = message;
    return cell;
}

// 编辑完成时触发该方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete){
        // 删除操作
        _deleteMessage = [_messageArray objectAtIndex:indexPath.row];
        self.viewModel.messageId = _deleteMessage.messageId;
        [self.viewModel.deleteMessageCommand execute:nil];
    }
}
// 返回值决定了该cell的编辑状态
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(_messageType == ZYMessageTypeDevice){
        return UITableViewCellEditingStyleDelete;
    }else{
       return UITableViewCellEditingStyleNone;
    }
    
}

// 返回值将作为删除指定cell时确定按钮的文本
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    return [language getStringByKey:LC_DELETE_BUTTON_TITLE];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(![tableView isEditing]){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}


#pragma mark -Getter

-(ZYMessageViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYMessageViewModel alloc] init];
    }
    return _viewModel;
}

@end
